import {
  View,
  Text,
  SafeAreaView,
  StyleSheet,
  ScrollView,
  Image,
  TextInput,
  Pressable,
  ActivityIndicator,
  Alert,
  Dimensions,
} from "react-native";
import React, { useState } from "react";
import Icon from "react-native-vector-icons/Ionicons";
import { NativeStackNavigationProp } from "@react-navigation/native-stack";
import { launchCamera, launchImageLibrary } from "react-native-image-picker";
import { uploadApi } from "../../api/upload";
import { postArticleApi } from "../../api/article";
import { BASE_URL } from "../../config";

type Props = {
  navigation: NativeStackNavigationProp<any>;
};

export default function DynamicPublic({ navigation }: Props) {
  // 设置头部信息
  navigation.setOptions({
    headerLeft(props) {
      return (
        <Pressable onPress={() => navigation.goBack()}>
          <Icon name="chevron-back" size={24} color="#087f5b" />
        </Pressable>
      );
    },
    headerRight(props) {
      return (
        <Pressable>
          <Icon name="warning-outline" size={20} color="#087f5b"></Icon>
        </Pressable>
      );
    },
  });

  const maxCover = 9;

  const [isLoadding, setIsLoadding] = useState(false); // 是否正在加载
  const [title, setTitle] = useState(""); // 标题
  const [content, setContent] = useState(""); // 内容
  const [covers, setCovers] = useState<string[]>([]); // 封面
  const [address, setAddress] = useState<string>(); // 地址
  const [status, setStatus] = useState<number>(0); // 状态 -1 为草稿 0为公开
  const [topicId, setTopicId] = useState<string>(); // 话题id

  // 上传图片
  async function uploadImageFn() {
    if (covers.length >= maxCover) return;

    launchImageLibrary(
      {
        mediaType: "photo",
        quality: 0.5,
        selectionLimit: maxCover - covers.length,
      },

      async (response) => {
        // 如果有取消
        // if (response.didCancel) {
        //   Alert.alert('yi xu xia');
        //   return '已取消';
        // }
        // console.log(response)
        console.log(response.assets![0]);
        const formData = new FormData();

        response.assets?.forEach((item) => {
          formData.append("files", {
            uri: item.uri,
            type: item.type,
            name: item.fileName,
          });
        });

        // 上传
        setIsLoadding(true);
        const res = await uploadApi<string[]>(formData);
        setIsLoadding(false);
        console.log(res);
        if (res.code == 200) {
          Alert.alert("上传成功");
          setCovers([...covers, ...res.data]);
        } else {
          Alert.alert("上传失败", res.message);
        }
      }
    );
  }

  // 提交按钮
  async function addSubmit() {
    if (covers.length === 0) {
      Alert.alert("请上传封面");
      return;
    }
    if (title.length === 0) {
      Alert.alert("请输入标题");
      return;
    }
    if (content.length === 0) {
      Alert.alert("请输入内容");
      return;
    }
    const res = await postArticleApi({
      title,
      content,
      covers,
    });
    console.log(res);
    if (res.code == 200) {
      Alert.alert("发布成功");
      navigation.navigate("Home");
    } else {
      Alert.alert("发布失败", res.message);
    }
  }

  return (
    <>
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.dynamic} showsVerticalScrollIndicator={false}>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            style={styles.dynamicListScroll}
          >
            <View style={styles.dynamicList}>
              {covers.map((item) => {
                return (
                  <View style={styles.coverItem}>
                    <Image
                      style={styles.coverItemImage}
                      source={{
                        uri: BASE_URL + item,
                      }}
                    />
                  </View>
                );
              })}
              {covers.length < maxCover && (
                <Pressable
                  onPress={() => uploadImageFn()}
                  style={styles.coverLaster}
                >
                  <Icon name="images-outline" size={32} color="#888"></Icon>
                </Pressable>
              )}
            </View>
          </ScrollView>
          <View style={styles.dynamicTitle}>
            <TextInput
              style={styles.dynamicTitleTextInput}
              placeholder="填写标题会获得更多赞哦～"
              value={title}
              onChangeText={(text) => {
                setTitle(text);
              }}
              maxLength={20}
            />
            <Text style={styles.dynamicTitleText}>{title.length}/20</Text>
          </View>
          <View style={styles.dynamicDesc}>
            <TextInput
              style={styles.dynamicDescTextInput}
              numberOfLines={10}
              multiline={true}
              placeholder="分享你的生活，发布运动相关的图文、旅游、攻略"
              value={content}
              onChangeText={(Text) => {
                setContent(Text);
              }}
            />
          </View>
          <View style={styles.dynamicTips}>
            <View style={styles.dynamicTipsItem}>
              <Icon
                name="sparkles-outline"
                size={18}
                color="#000"
                style={styles.dynamicTipsItemIcon}
              ></Icon>
              <Text style={styles.dynamicTipsItemTitle}>状态</Text>

              <Text style={styles.dynamicTipsItemText}>公开</Text>
              <Icon name="chevron-forward-outline" size={16} color="#333" />
            </View>
            <View style={styles.dynamicTipsItem}>
              <Icon
                name="chatbubble-ellipses-outline"
                size={18}
                color="#000"
                style={styles.dynamicTipsItemIcon}
              ></Icon>
              <Text style={styles.dynamicTipsItemTitle}>选话题</Text>
              <View style={styles.dynamicTipsItemTips}>
                <Icon name="earth" size={16} color="#5f3dc4" />
                <Text style={styles.topicText}>自律的路上越走越远</Text>
              </View>
              <Icon name="chevron-forward-outline" size={16} color="#333" />
            </View>
            <View style={styles.dynamicTipsItem}>
              <Icon
                name="location-outline"
                size={18}
                color="#000"
                style={styles.dynamicTipsItemIcon}
              ></Icon>
              <Text style={styles.dynamicTipsItemTitle}>在哪里</Text>
              <Icon name="chevron-forward-outline" size={16} color="#333" />
            </View>
          </View>
        </ScrollView>
        <View style={styles.fixedBottom}>
          <Pressable onPress={addSubmit} style={styles.fixedBottomBtn}>
            <Text style={styles.fixedBottomBtnText}>发布</Text>
          </Pressable>
        </View>
        {isLoadding && (
          <View style={styles.loading}>
            <ActivityIndicator size="small" color="#087f5b" />
            <Text style={styles.loadingText}>上传中...</Text>
          </View>
        )}
      </SafeAreaView>
    </>
  );
}

const styles = StyleSheet.create({
  loading: {
    alignItems: "center",
    justifyContent: "center",
    position: "absolute",
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height,
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 9999,
  },
  loadingText: {
    color: "#087f5b",
    fontSize: 12,
    marginTop: 10,
    paddingBottom: 50,
  },
  container: {
    flex: 1,
  },
  dynamic: {},
  dynamicListScroll: {
    backgroundColor: "#fff",
    // width:300
  },
  dynamicList: {
    flexDirection: "row",
    padding: 10,
    // backgroundColor: "red",
  },
  coverItem: {
    width: 88,
    height: 88,
    marginRight: 6,
    borderRadius: 6,
    overflow: "hidden",
  },
  coverItemImage: {
    width: "100%",
    height: "100%",
  },
  coverLaster: {
    width: 88,
    height: 88,
    backgroundColor: "#eee",
    borderRadius: 6,
    justifyContent: "center",
    alignItems: "center",
  },
  dynamicTitle: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    // marginTop: 10,
    paddingVertical: 20,
    borderBottomWidth: 1,
    borderBlockColor: "#eee",
    padding: 10,
    backgroundColor: "#fff",
  },
  dynamicTitleTextInput: {
    fontSize: 16,
    fontWeight: "bold",
    paddingRight: 20,
    flex: 1,
  },
  dynamicTitleText: {
    fontSize: 12,
    color: "#888",
  },
  dynamicDesc: {
    paddingVertical: 20,
    padding: 10,
    backgroundColor: "#fff",
  },
  dynamicDescTextInput: {
    fontSize: 16,
    paddingRight: 20,
    height: 260,
    // backgroundColor:'red'
  },
  dynamicTips: {
    backgroundColor: "#fff",
    padding: 10,
    marginTop: 10,
    paddingBottom: 100,
  },
  dynamicTipsItem: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
  },
  dynamicTipsItemIcon: {
    marginRight: 6,
    paddingLeft: 4,
  },
  dynamicTipsItemTitle: {
    color: "#000",
    flex: 1,
    fontSize: 16,
  },
  dynamicTipsItemTips: {
    flexDirection: "row",
    backgroundColor: "#d0bfff",
    paddingVertical: 4,
    paddingHorizontal: 6,
    borderRadius: 20,
    alignItems: "center",
  },
  topicText: {
    fontSize: 14,
    color: "#5f3dc4",
    marginLeft: 4,
    paddingRight: 8,
  },
  dynamicTipsItemText: {
    fontSize: 14,
    color: "#333",
  },
  fixedBottom: {
    position: "absolute",
    left: 0,
    right: 0,
    bottom: 0,
    paddingTop: 20,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#fff",
  },
  fixedBottomBtn: {
    backgroundColor: "#0ca678",
    width: "80%",
    alignItems: "center",
    paddingVertical: 14,
    borderRadius: 100,
    marginBottom: 20,
  },
  fixedBottomBtnText: {
    color: "#fff",
    fontSize: 16,
  },
});
